<template>
    <template v-if="field ==='modelType'">
        <n-form-item label="AI 模型">
            <jb-select url="aiResource/listAllEnabledType" labelField="name" placeholder="请选择AI模型" valueField="sn"
                       v-model:value="model.model"></jb-select>
        </n-form-item>
    </template>
    <template v-if="field ==='promptTpl'">
        <n-form-item label="问题">
            <n-select placeholder="请选择问题" clearable v-model:value="model.inputField"
                      :options="prevOutputFieldOptions"></n-select>
        </n-form-item>
    </template>
    <template v-if="field ==='promptTpl'">
        <div @mousedown.stop @wheel.stop v-if="model.inputField === 'jb_custom'">
            <div class="flex justify-between mb-1.5">
                <label>提示词</label>
                <n-popselect
                    v-model:value="insertValue"
                    :options="insertQuestionOptions"
                    size="medium"
                    scrollable
                >
                    <n-button strong secondary type="success" size="tiny">
                        <jb-icon :local="true" icon="jam:plus-circle"></jb-icon>
                        插入变量
                    </n-button>
                </n-popselect>
            </div>
            <textarea v-model="model.promptTpl" type="textarea" ref="textarea" :rows="8"
                      placeholder="向AI提问的内容，如果留空，则默认使用用户的提问。&#13;&#10;可以通过 ${输出字段名} 引入其他节点的输出内容。"
            ></textarea>
        </div>
    </template>
    <template v-if="field ==='outputToResponse'">
        <div class="mt-8 mb-8 fx fx-m_between">
            <label>是否输出到客户端</label>
            <n-switch v-model:value="model.outputToResponse"/>
        </div>
        <template v-if="model.outputToResponse ==true">
            <div class="mt-8 mb-8 fx fx-m_between">
                <label>是否使用流式输出</label>
                <n-switch v-model:value="model.stream"/>
            </div>
        </template>
    </template>

    <!--    <template v-if="field ==='stream'&&model.outputToResponse==true">-->
    <!--        <div class="mt-8 mb-8 fx fx-m_between">-->
    <!--            <label>是否使用流式输出</label>-->
    <!--            <n-switch v-model:value="model.stream"/>-->
    <!--        </div>-->
    <!--    </template>-->
    <template v-if="field ==='useContext'">
        <div class="mt-8 mb-8 fx fx-m_between">
            <label>是否根据上下文进行回答</label>
            <n-switch v-model:value="model.useContext"/>
        </div>
    </template>
    <template v-if="field ==='persistDb'">
        <div class="mt-8 mb-8 fx fx-m_between">
            <label>是否将AI回答保存到数据库</label>
            <n-switch v-model:value="model.persistDb"/>
        </div>
    </template>
    <template v-if="field ==='systemRole'">
        <n-form-item label="系统角色">
            <n-input   @mousedown.stop @wheel.stop   v-model:value="model.systemRole" type="textarea" placeholder="请输入系统角色" rows="6"
            ></n-input>
        </n-form-item>
    </template>
    <template v-if="field ==='maxTokens'">
        <n-form-item label="MaxToken值">
            <div style="display: flex;flex-direction: column;width: 100%">
                <n-input-number round style="width: 100%" v-model:value="model.maxTokens" placeholder="请输入MaxToken值"
                                :max="maxTokensMax" :min="1">
                    <template #suffix>
                        tokens
                    </template>
                </n-input-number>
                <span class="text-gray-400 font-12 pad-5 bg-gray-50 rounded-lg mt-1"
                      >范围: 1 - {{ maxTokensMax }}</span>
            </div>
        </n-form-item>
    </template>
    <template v-if="field === 'temperature'">
        <n-form-item label="Temperature" path="">
            <n-input-number round style="width: 100%"
                            v-model:value="model.temperature" :step="0.1" :precision="2" :max="2" :min="0.1"
                            placeholder="请输入Temperature值">
            </n-input-number>
        </n-form-item>
    </template>
    <template v-if="field === 'topP'">
        <n-form-item label="Top P" path="">
            <div style="display: flex;flex-direction: column">
                <n-slider v-model:value="model.topP" :step="0.1" :max="1"/>
                <span class="text-gray-400 font-12 pad-5 bg-gray-50 rounded-lg mt-1">调节句子生成的多样性，值越大生成的内容越丰富多样，但它和Temperature只能设置一个。当前
					{{ temperatureSet ? 'Temperature已设置' : 'Top P已设置' }} </span>
            </div>
        </n-form-item>
    </template>
    <template v-if="field === 'topK'">
        <n-form-item label="Top K" path="">
            <div style="display: flex;flex-direction: column">
                <n-input-number round style="width: 100%" :precision="0" v-model:value="model.topK"
                                placeholder="请输入TopK值" :max="100">
                </n-input-number>
                <span class="text-gray-400 font-12 pad-5 bg-gray-50 rounded-lg mt-1">限制每次生成时考虑的词汇数量，值越大创造性越强。该选项不是所有大模型都支持。</span>
            </div>
        </n-form-item>
    </template>
</template>

<script setup>
import {
    useVueFlow
} from '@vue-flow/core'
import {
    computed,
    ref,
    inject,
    onMounted,
    watch, nextTick
} from 'vue';
import {
    getNodeOutputFieldNames
} from '../../node-def'

const flow = useVueFlow();


const currentNodeId = inject('currentNodeId');


const props = defineProps({
    field: {
        type: String,
        required: true
    },
    maxTokensMax: {
        type: Number,
        default: 8192
    }
});


const model = defineModel();


const temperatureSet = computed(() => model.value.temperature !== undefined);

/** 获取所有前置节点的输出字段，并生成下拉选项 */
const prevOutputFieldOptions = ref([{
    label: "自定义问题",
    value: "jb_custom"
}])


watch(() => flow.getEdges.value, (newV) => {
    console.debug("监听到edge改动", newV)
    updatePrevOutputFieldOptions(currentNodeId);
})
//监听prevOutputFieldOptions
watch(() => prevOutputFieldOptions.value, (newV) => {
    //如果数组是空值,则清空input的值
    if (newV.length === 0) {
        model.value.inputField = null;
        //清空输入框
    }
    //默认追加一个自定义的问题
    prevOutputFieldOptions.value.push({
        label: "自定义问题",
        value: "jb_custom"
    });

})
flow.onEdgesChange(events => {
    console.debug("intention init", events)
    if (events.some(item => item.type === 'remove' || item.type === 'add')) {
        prevOutputFieldOptions.value = [];
        insertQuestionOptions.value = []
        updatePrevOutputFieldOptions(currentNodeId);
    }
})


function updatePrevOutputFieldOptions(sourceNodeId) {
    const connections = flow.getConnectedEdges(sourceNodeId).filter(edge => edge.targetNode.id == sourceNodeId);
    console.debug(connections, "connections")
    // 遍历所有前置连接
    connections.forEach(connection => {
        const sourceNode = connection.sourceNode;
        if (sourceNode) {
            // 获取该类型节点的所有输出字段名称
            const outputFields = getNodeOutputFieldNames(sourceNode.type);
            // 从sourceNode.data中获取对应字段的值
            outputFields.forEach(fieldPath => {
                // 处理嵌套字段路径，如 "llmConfig.outputField"
                const value = fieldPath.split('.').reduce((obj, key) => obj && obj[key], sourceNode
                    .data);
                if (value) {
                    if (prevOutputFieldOptions.value.some(item => item.value === value) == false) {
                        prevOutputFieldOptions.value.unshift({
                            label: value,
                            value: value
                        });
                        insertQuestionOptions.value.unshift({
                            label: value,
                            value: value
                        })
                    }
                }
            });
            console.log(prevOutputFieldOptions.value, "Ai的llmConfig的意图是被数组")
            updatePrevOutputFieldOptions(connection.source)
        }
    });
}


/** 获取所有前置节点的输出字段，并生成下拉选项 */


/**动态插入变量-----------------------------*/
//变量数组
const insertValue = ref('')
const insertQuestionOptions = ref([])
const textarea = ref(null);
//选中值,就在光标的指定位置插入值
watch(() => insertValue.value, (newV) => {
    if (newV != "") {
        insertText('${' + newV + '}');
    }
    insertValue.value = '';
})
// 在指定位置插入变量
const insertText = (insertText) => {
    // 确保textarea元素存在
    if (!textarea.value) return;

    // 初始化inputTpl，防止null或undefined的情况
    if (!model.value.promptTpl) {
        model.value.promptTpl = '';
    }

    // 获取光标起始位置和结束位置
    const startPos = textarea.value.selectionStart;
    const endPos = textarea.value.selectionEnd;

    // 插入文本到光标位置后
    const beforeText = model.value.promptTpl.substring(0, startPos);
    const afterText = model.value.promptTpl.substring(endPos, model.value.promptTpl.length);

    // 更新textarea的值
    model.value.promptTpl = beforeText + insertText + afterText;

    // 更新光标位置
    nextTick(() => {
        textarea.value.focus();
        textarea.value.setSelectionRange(startPos + insertText.length, startPos + insertText.length);
    });
};
/**动态插入变量-----------------------------*/
onMounted(() => {
    updatePrevOutputFieldOptions(currentNodeId); //1.初始化的修改数组
});
</script>

<style scoped>
.fx {
    display: flex;
}

.fx- m_between {
    justify-content: space-between;
    align-items: center;
}

.flex-col {
    display: flex;
    flex-direction: column;
}

textarea {
    width: 100%;
    border-radius: 3px;
    border: 1px solid #bfbfc2;
    padding: 5px;
     /* scrollbar-width: none;控制滚动条的宽度：auto | thin | none */
}

textarea:focus {
    border: 1px solid #18a058 !important;
    outline: none;
}

</style>